﻿using DotNetty.Buffers;
using DotNetty.Codecs;
using DotNetty.Transport.Channels;
using JT809.Protocol;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JTT809_2011_Service.JT809
{
    /// <summary>
    /// JT809编码
    ///  头标识	      数据头	    数据体	    CRC校验码	    尾标识
    /// BeginFlag   JT809Header   JT809Bodies    CRCCode        EndFlag
    ///    5B  	         -	          -	            -	          5D
    /// </summary>
    internal class JT809Encoder : MessageToByteEncoder<JT809Response>
    {
        private readonly ILogger<JT809Encoder> _logger;
        private readonly JT809Serializer _JT809Serializer;

        #region ctor
        public JT809Encoder
            (
                IJT809Config jt809Config,
                ILoggerFactory loggerFactory
            )
        {
            _JT809Serializer = jt809Config.GetSerializer();
            _logger = loggerFactory.CreateLogger<JT809Encoder>();
        }


        #endregion

        protected override void Encode(IChannelHandlerContext context, JT809Response message, IByteBuffer output)
        {
            if (message.Package != null)
            {
                var sendData = _JT809Serializer.Serialize(message.Package, message.MinBufferSize);
                SenDataAndLog(output, sendData);
            }
            else if (message.HexData!=null)
            {
                SenDataAndLog(output, message.HexData);
            }
        }

        private void SenDataAndLog(IByteBuffer output, byte[] sendData)
        {
            if (_logger.IsEnabled(LogLevel.Trace))
            {
                //记录日志
                _logger.LogTrace(ByteBufferUtil.HexDump(sendData));
            }
            output.WriteBytes(sendData);
        }
    }
}
